<template>
	<view class="wrap">
		<view class="container" >
			<scroll-view 
				v-if="loaded"
				class="content"
				scroll-y="true" style="width: 100%;height:80vh;" :scroll-top="scrollTop">
				<!-- 用来获取消息体高度 -->
				<view id="chat-list" >
					<!-- 消息 -->
					<view class="item" v-for="(x,i) in msgList" :key="i">
						<!-- 用户消息 头像可选加入-->
						<view v-if="x.type===0">
							<view v-if="x.my" class="chat-item human-item">
								<!-- 	<image v-if="!x.my" class="chat-img" src="../../static/..." mode="aspectFill" ></image> -->

								<view class="chat chat-human">
									<text style="word-break: break-all;" @longpress="copyText(x.msg)">{{x.msg}}</text>
								</view>
								<!-- <image class="chat-img " src="../../static/..." mode="aspectFill" ></image> -->
							</view>
							<!-- 机器人消息 -->
							<view v-if="!x.my" class="chat-item ai-item">
								 <view class="chat-img flex-row-center">
									<image style="height: 75rpx;width: 75rpx;" src="../../static/robt.png" mode="aspectFit"></image>
								</view>
								<view class="chat chat-ai">
									<text style="word-break: break-all;" @longpress="copyText(x.msg)">{{x.msg}}</text>
								</view>
								<view style="position: relative; bottom:-20px;">
									<u-button type="primary" customStyle="height:40px;width:80px"
											shape="circle" icon="server-man" style="font-size: 2px;" @click="generateVideo(x.msg)">
											生成视频
									</u-button>
								</view>
							</view>
						</view>
						<view v-if="x.type===1">
							<view class="chat-item ai-item">
								 <view class="chat-img flex-row-center">
									<image style="height: 75rpx;width: 75rpx;" src="../../static/robt.png" mode="aspectFit"></image>
								</view>
								<view class="chat chat-ai chat-video">
									<video  :show-fullscreen-btn="false" show-center-play-btn="true" :src="x.videoUrl"></video>
								</view>
							</view>
						</view>
					</view>
					<!-- loading是显示 -->
					<view v-show="msgLoad" class="">
						 <view class="chat-img flex-row-center">
							<image style="height: 75rpx;width: 75rpx;" src="../../static/robt.png" mode="aspectFit">
							</image>
						</view>
						<view class="chat-item ai-item">
							<view class="chat chat-ai" >
								<u-loading-icon color="#1cbbb4" :size="18"></u-loading-icon>
							</view>
						</view>
					</view>
					<!-- 防止消息底部被遮 -->
					<view style="height: 110rpx;">

					</view>
				</view>

			</scroll-view>
		</view>
		<view class="bottom-textarea" :style="{bottom: inputBottom+'px'}">
			<!-- 底部导航栏 -->
			<view id="bottom" style="position: absolute;bottom:20rpx;width: 100%;'">
				<view class="bottom-panel">
					<!-- vue无法使用软键盘"发送" -->
					<input v-model="msg" class="uni-input dh-input" type="text" style="background-color: #f0f0f0;" @confirm="check"
						confirm-type="send" placeholder-class="my-neirong-sm" placeholder="聊两句吧~"
						cursor-spacing="10"
						:adjust-position="false"
						:disabled="msgLoad"
						/>
					<u-button type="primary" :plain="true" @click="check" :disabled="msgLoad" 
					:customStyle="{'width':'120rpx','marginLeft':'15rpx'}" shape="circle"
					color="#1cbbb4" icon="play-right"></u-button>

					<u-button type="info"   :disabled="msgLoad" class="btn" shape="circle" @click="showDrawer"
					:customStyle="{'width':'120rpx','marginLeft':'15rpx'}"
					icon="server-man">视频</u-button>
					
				</view>
			</view>
					<u-toast ref="uToast"></u-toast>
				</view>
		<uni-drawer ref="showRight" mode="right" :mask-click="true" :width='500'>
			<scroll-view style="height: 100%;" scroll-y="true">				
				<u-button @click="closeDrawer" type="primary">关闭</u-button>		
				<view class="voice">
					<text>说话人:</text>
					<view class="selector">
					<uni-data-select v-model="value" :localdata="ttsList" @change="voiceChange" placeholder="请选择语音包"></uni-data-select>
					</view>
				</view>
				<u-line ></u-line>
				<view class="presenter">
					<text>表演人:</text>
					<view class="upload">
						<uni-file-picker 							
							fileMediatype="image" 
							limit="1"
							return-type="array"
							mode="grid" 
							@select="select" 
							@progress="progress" 
							@success="success" 
							@fail="fail" 
							:auto-upload="false"
							ref="files"
							>	
						<image v-if="imageValue!==''" mode="aspectFit" :src="'http://202.112.194.53:9999/' + imageValue"></image>
					</uni-file-picker>							
							<u-button class="submit" type="success" @click="submitActor"  shape="circle">选为表演人</u-button>
					</view>
				</view>
				<u-line ></u-line>
				<u-button @click="generateVideo(msg)">生成视频</u-button>
			</scroll-view>
		</uni-drawer>
	</view>
</template>

<script>
	import io from '@hyoga/uni-socket.io';
	export default {
		data() {
			return {				
				loaded:true,
				scrollTop:1000,
				history:[],
				// type 0 文本 1 视频
				msgList:[{
					type:0,
					my: false,
					msg: "你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?你好，我是超级智能，请问有什么可以帮到你?"
				},{
					type:0,
					my: true,
					msg: "一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,一曲忠诚的赞歌,"
				},
				{
					type:1,
					my: false,
					videoUrl:"http://202.112.194.53:9999/outputs/2023-09-25/k4g3IONQxsrwAeJ6AAAB/2023_09_25_04.27.31/result.mp4"
				},],
				msgLoad: false,
				inputBottom:10,
				msg:"",
				show:true,
				// limit:false,
				value: 0,
				ttsList: [
					{ value: 0, text: "普通话-女-小小",label:"zh-CN-XiaoxiaoNeural"}, //zh-CN-XiaoxiaoNeural
					{ value: 1, text: "普通话-女-小伊",label:"zh-CN-XiaoyiNeural"}, //zh-CN-XiaoyiNeural
					{ value: 2, text: "普通话-男-云剑",label:"zh-CN-YunjianNeural"}, //zh-CN-YunjianNeural
					{ value: 3, text: "普通话-男-云熙",label:"zh-CN-YunxiNeural"}, //zh-CN-YunxiNeural
					{ value: 4, text: "普通话-女-云侠",label:"zh-CN-YunxiaNeural"},//zh-CN-YunxiaNeural
					{ value: 5, text: "普通话-女-云阳",label:"zh-CN-YunyangNeural"},//zh-CN-YunyangNeural
					{ value: 6, text: "辽宁话-女-小贝",label:"zh-CN-liaoning-XiaobeiNeural" },//zh-CN-liaoning-XiaobeiNeural
					{ value: 7, text: "陕西话-女-小妮",label:"zh-CN-shaanxi-XiaoniNeural" },//zh-CN-shaanxi-XiaoniNeural
					{ value: 8, text: "粤语-女-HiuGaai",label:"zh-HK-HiuGaaiNeural" },//zh-HK-HiuGaaiNeural
					{ value: 9, text: "粤语-女-HiuMaan",label:"zh-HK-HiuMaanNeural"},//zh-HK-HiuMaanNeural
					{ value: 10, text: "粤语-男-WanLung",label:"zh-HK-WanLungNeural" },//zh-HK-WanLungNeural
					{ value: 11, text: "台湾腔-女-HsiaoChen",label:"zh-TW-HsiaoChenNeural" },//zh-TW-HsiaoChenNeural
					{ value: 12, text: "台湾腔-女-HsiaoYu",label:"zh-TW-HsiaoYuNeural"},//zh-TW-HsiaoYuNeural
					{ value: 13, text: "台湾腔-男-YunJhe",label:"zh-TW-YunJheNeural"},//zh-TW-YunJheNeural
					
				],						
				imageValue:"",
				ttsVal:"zh-CN-XiaoxiaoNeural",
				filePath:""
			}
		},
		
		onNavigationBarButtonTap(e) {				
			if(e.index == '0'){
				console.log("show drawer")
				this.showDrawer()
			}
		},
		onLoad() {
		},
		methods: {
			check(){
				// 消息为空不做任何操作
				if (this.msg == "") {
					return;
				}
				
				this.sendMsg()

			},
			sendMsg() {
				let that = this
				// 消息为空不做任何操作
				if (this.msg == "") {
					return;
				}

				this.msgList.push({
					'type':0,
					"msg": this.msg,
					"my": true
				})
				this.msgLoad = true

				let params = {
					msg:this.msg,
					notip:true
				}				
				let query = that.msg
				that.msg = ""
				this.scrollToButtom();
				uni.request({
					url:"http://202.112.194.53:9999/chat",
					header: {
						"Content-Type": "application/x-www-form-urlencoded"
					}, 
					data:{
						"query":query,
						"history": JSON.stringify(that.history) 
					},
					method:"POST",
					success(res) {
						console.log(res.data)
						let newMsg = []
						// that.history = res.data['history']
						// for(let i=0;i<res.data['history'].length;i++){
						// 	let qa = res.data['history'][i]
						// 	newMsg.push({
						// 		'type':0,
						// 		"msg": qa[0],
						// 		"my": true
						// 	})
						// 	newMsg.push({
						// 		'type':0,
						// 		"msg": qa[1],
						// 		"my": false
						// 	})
						// }						
						that.msgList.push({
							'type':0,
							'msg':res.data['response'],
							"my":false
						})
					},
					fail(res) {
						console.log(res)
					},
					complete() {						
						that.limit = true;
						that.msgLoad = false
						that.scrollToButtom();
					}
					
				})
				
			},
			scrollToButtom() {
				this.scrollTop += 1; //滚到底部
				/*
				const query = uni.createSelectorQuery().in(this);
				let nodesRef = query.select('#chat-list');
				nodesRef
					.boundingClientRect(res => {
						this.$nextTick(() => {
							//进入页面滚动到底部
							this.scrollTop = res.height;
						});
					})
					.exec();*/
			},
			copyText(msg) {
				uni.setClipboardData({
				data:msg,
				success() {
					uni.showToast({
						title:'已复制到剪贴板',
						icon:'none',
						position:'top'
							})
						}
					})
			},
			generateVideo(content){
				let that = this
				if(content===""){
					uni.showToast({
						title:"请输入文字",
						icon:"error"
					})
					return
				}
				let socket = io('https://classtest.blcu.edu.cn/', {
				  query: {},
				  transports: [ 'websocket', 'polling' ],
				  timeout: 12000,
				});
				socket.on('connect_error', (msg) => {
				  console.log('connect_error', msg);
				  that.msgLoad = false
				  socket.disconnect()
				  uni.showToast({
				  	title:"连接失败，请稍后再试",
					icon:'error',						
				  })
				});
				socket.on('connect', () => {
				  // ws连接已建立，此时可以进行socket.io的事件监听或者数据发送操作
				  // 连接建立后，本插件的功能已完成，接下来的操作参考socket.io官方客户端文档即可
				  console.log('ws 已连接');
				  // socket.io 唯一连接id，可以监控这个id实现点对点通讯
				  const { id } = socket;
				  socket.on(id, (message) => {
				    // 收到服务器推送的消息，可以跟进自身业务进行操作
				    console.log('ws 收到服务器消息：', message);
				  });
				  socket.on("ai_response", (message) => {
				    // 收到服务器推送的消息，可以跟进自身业务进行操作
				    console.log('ai response：', message);
					console.log(message['audio_url'])
					console.log(message['video_url'])
					that.msgList.push({
						'type':1,
						'my':false,
						'videoUrl':"http://202.112.194.53:9999/" + message['video_url']						
					})
					socket.disconnect()
					that.msgLoad = false
					that.scrollToButtom()
				  });
				  // 主动向服务器发送数据
				  socket.emit('generate_ai',{'content':content,'tts':that.ttsVal,'actor':that.imageValue} );
				  that.msgLoad = true
				});
				
			},
			showDrawer() {
				this.$refs.showRight.open();
			},
			closeDrawer() {
				this.$refs.showRight.close();
			},
			confirm(e){
				console.log(e)
			},
			voiceChange(e) {
				console.log("e:", e);
				if(e!==''){
					this.ttsVal = this.ttsList[e].label
					console.log(this.ttsList[e].label)
				}					
			},
			submitActor(){
				let that = this
				uni.showLoading({
					title:"上传中...",
					mask:true
				})
				uni.uploadFile({
					url:"http://202.112.194.53:9999/upload",
					filePath: that.filePath,
					name: 'file',
					formData: {						  
					  date: new Date().getTime(),
					  id: this.id
					},
					success(res) {
						let result = JSON.parse(res.data)
						console.log(result)
						that.imageValue =  result['img']
						uni.hideLoading()
						uni.showToast({
							title:"已更换说话人",
							icon:"success"
						})							
					},				
					finally(){
						uni.hideLoading()
					}
				})
			},
			// 获取上传状态
			select(e){
				console.log('选择文件：',e)			
				this.filePath = e.tempFiles[0].path
									
			},
			// 获取上传进度
			progress(e){
				console.log('上传进：',e)				
			},
			
			// 上传成功
			success(e){
				console.log('上传成功')
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			}
		}
	}
</script>

<style>
	.container {
	  display: flex;
	  flex-direction: column;
	}
	.content {
	    flex-grow: 1;
	    overflow: auto;
		background-color: black;
	}
	.chat-item{
		display:flex;
	}
		
	.human-item{
		justify-content: flex-end;
	}
		
	.chat {
		padding: 8px 12px;
		margin:5px 10px 5px 10px;
		font-size:14px;
		max-width: 40vw;
	}
		
	.item:first-child .chat{
		margin-top: 20px;
	}
	.chat-human{
		border-radius: 18px 0px 18px 18px;
		background-color: #1cbbb4;
		color:#fff;
	}

	.chat-ai{
		border-radius: 0px 18px 18px 18px;
		background-color: #f9f9f9;
	}
	.bottom-textarea {
	  position: fixed;
	  bottom: 0px;
	  left: 0px;
	  right: 0px;
	  display: flex;
	}
	.dh-input {
		width: 85%;
		height: 8vh;
		border-radius: 10rpx;
		padding-left: 25rpx;
		margin-left: 15rpx;
		
		background-color: #FFFFFF;
		font-size:14px;		
	}
	.bottom-panel{
		font-size: 55rpx;display:flex;margin:6px;
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: space-evenly;
		align-items: center;
	}
	.selector{
		width: 300px;
	}
	.voice{
		display: flex;
		flex-direction: row;
		margin: 20px;
		align-items: center;
		justify-content: space-evenly;		
	}
	.presenter{		
		display: flex;
		flex-direction: column;
		margin: 20px;
		justify-items: center;
		align-content: space-evenly;
	}
	.upload{
		display: flex;
		flex-direction: column;
		align-content: flex-start;
		margin: 10px;
	}
	.submit{
		margin: 10px;
		width: 120px;
	}
</style>
